import * as express from 'express';
import * as  fs from 'fs';
import * as  path from 'path';
import * as  bodyParser from "body-parser";

import { App } from "../framework/framework";
import { appSettings } from '../app/main';
import { ClientStore } from "../app/logics/logic";

const exp = express();
const config = JSON.parse(fs.readFileSync(path.join(__dirname, './config.json')).toString());

var _res: any;
const lgcStore = new ClientStore("../../clientStore.json");

function main() {

    var app;

    // request post parser
    exp.use(bodyParser.urlencoded({ extended: true }));

    exp.get('/*', authentication, function (req, res, next) {
        let reg = new RegExp(/^[a-z0-9_\/%.]+$/i);

        if (reg.test(req.url)) {

            // 跨域
            res.header("Access-Control-Allow-Origin", "*");
            res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            res.header('Access-Control-Allow-Headers', 'Content-Type');

            next();
        } else {
            res.sendStatus(404).end();
        }
    }, function (req, res) {
        // 保留引用
        _res = res;
        var url = req.url.substr(1);

        app.triggerRouteChange(url);
    });
    exp.post('/*', authentication, function (req, res, next) {
        let reg = new RegExp(/^[a-z0-9_\/]+$/i);

        if (reg.test(req.url)) {

            // 跨域
            res.header("Access-Control-Allow-Origin", "*");
            res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            res.header('Access-Control-Allow-Headers', 'Content-Type');

            next();
        } else {
            res.sendStatus(404).end();
        }
    }, function (req, res) {
        // 保留引用
        _res = res;

        var url = req.url.substr(1);

        app.triggerRouteChange(url, req.body);
    });

    var server = exp.listen(config.servicePort, config.serviceDomain, function () {

        var house = server.address().address;
        var port = server.address().port;

        app = new App(appSettings);

        app.initialize();

        // 订阅
        app.onSendJson((topic: any, data: any) => {
            _res.json(data);
            _res.end();
        });
        app.onSendError((topic: any, e: any) => {
            if (e.toString().indexOf('Controller not found:') !== -1) {
                // error 404
                _res.sendStatus(404).end();
            } else {
                _res.send("Sorry! there has been an error please check out the console for more info!").end();
            }
        });

        console.log(`应用监听，访问地址：http://${house}:${port}`)
    });

}
function authentication(req, res, next) {

    let token = req.header("token"), mark = false;

    if (token) {

        if (lgcStore.hasValid(token)) {
            mark = true;
        }
    }

    if (mark) {
        next();
    } else {
        res.sendStatus(404).end();
    }
}
main();